﻿using MatlabWork.Dal;
using MatlabWork.Entity;
using MatlabWork.Model;
using Microsoft.Win32;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media.Animation;
using TestingPlatForm.MissionContrl.Entity;
using TestingPlatForm.MissionContrl.Models;

namespace TestingPlatForm.MissionContrl.ViewModels
{
    public class IndexViewModel : BindableBase
    {
        private readonly IEventAggregator _eventAggregator;
        public IndexViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;
            _eventAggregator.GetEvent<DictionaryTransferEvent>().Subscribe(OnDictionaryTransferred, ThreadOption.UIThread);
            visable = Visibility.Collapsed;
            visibility = Visibility.Collapsed;
            TimeSpanVisable = Visibility.Collapsed;
        }

        private void OnDictionaryTransferred(DictionaryTransferEventArgs e)
        {
            listDictionary = e.Data;
        }

        #region 参数变量
        public Dictionary<string, List<SateliteData>> listDictionary = new Dictionary<string, List<SateliteData>>();

        private int _startTime;

        public int startTime
        {
            get { return _startTime; }
            set { SetProperty(ref _startTime, value); }
        }

        private int _DelTime;

        public int DelTime
        {
            get { return _DelTime; }
            set { SetProperty(ref _DelTime, value); }
        }

        private int _DelValue;

        public int DelValue
        {
            get { return _DelValue; }
            set { SetProperty(ref _DelValue, value); }
        }

        private int _lastTime;

        public int lastTime
        {
            get { return _lastTime; }
            set { SetProperty(ref _lastTime, value); }
        }

        private string _FileName;

        public string FileName
        {
            get { return _FileName; }
            set { SetProperty(ref _FileName, value); }
        }

        private int _PreferTime;

        public int PreferTime
        {
            get { return _PreferTime; }
            set { SetProperty(ref _PreferTime, value); }
        }

        private bool _SateChecked;

        public bool SateChecked
        {
            get { return _SateChecked; }
            set { SetProperty(ref _SateChecked, value); }
        }
        
        private bool _MoveIsChecked;

        public bool MoveIsChecked
        {
            get { return _MoveIsChecked; }
            set { SetProperty(ref _MoveIsChecked, value); }
        }

        private bool _IsChecked;

        public bool IsChecked
        {
            get { return _IsChecked; }
            set { SetProperty(ref _IsChecked, value); }
        }

        private bool _SingleIsChecked;

        public bool SingleIsChecked
        {
            get { return _SingleIsChecked; }
            set { SetProperty(ref _SingleIsChecked, value); }
        }


        private bool _StIsChecked;

        public bool StIsChecked
        {
            get { return _StIsChecked; }
            set { SetProperty(ref _StIsChecked, value); }
        }

        private bool _RAHIsChecked;

        public bool RAHIsChecked
        {
            get { return _RAHIsChecked; }
            set { SetProperty(ref _RAHIsChecked, value); }
        }

        private bool _RatioIsChecked;

        public bool RatioIsChecked
        {
            get { return _RatioIsChecked; }
            set { SetProperty(ref _RatioIsChecked, value); }
        }

        private bool _TimeSpanIsChecked;

        public bool TimeSpanIsChecked
        {
            get { return _TimeSpanIsChecked; }
            set { SetProperty(ref _TimeSpanIsChecked, value); }
        }

        private bool _PreDel = false;

        public bool PreDel
        {
            get { return _PreDel; }
            set { SetProperty(ref _PreDel, value); }
        }

        private bool _AftDel = false;

        public bool AftDel
        {
            get { return _AftDel; }
            set { SetProperty(ref _AftDel, value); }
        }

        private ObservableCollection<Grid> dynamicControls = new ObservableCollection<Grid>();
        public ObservableCollection<Grid> DynamicControls
        {
            get { return dynamicControls; }
            set { SetProperty(ref dynamicControls, value); }
        }

        private Visibility _visibility;

        public Visibility visibility
        {
            get { return _visibility; }
            set { SetProperty(ref _visibility, value); }
        }

        private List<string> _selectedList = new List<string>();

        public List<string> selectedList
        {
            get { return _selectedList; }
            set { SetProperty(ref _selectedList, value); }
        }
        

        private Visibility _visable;

        public Visibility visable
        {
            get { return _visable; }
            set { SetProperty(ref _visable, value); }
        }

        private Visibility _TimeSpanVisable;

        public Visibility TimeSpanVisable
        {
            get { return _TimeSpanVisable; }
            set { SetProperty(ref _TimeSpanVisable, value); }
        }

        private double _timeSpan;

        public double timeSpan
        {
            get { return _timeSpan; }
            set { SetProperty(ref _timeSpan, value); }
        }

        #endregion

        private void HttpView_OnReceivedMessage(Dictionary<string, List<SateliteData>> keyValuePairs, string time)
        {
            listDictionary = keyValuePairs;
            FileName = time;
            InitialGrid();
        }

        public void InitialGrid()
        {
            DynamicControls.Clear();
            Grid grid = new Grid();
            int RowsCount = 12;
            int ColumnsCount = 9;
            while (RowsCount-- > 0)
            {
                RowDefinition rowDefinition = new RowDefinition();
                rowDefinition.Height = new GridLength();
                grid.RowDefinitions.Add(rowDefinition);
            }

            while (ColumnsCount-- > 0)
            {
                ColumnDefinition columnDefinition = new ColumnDefinition();
                columnDefinition.Width = new GridLength();
                grid.ColumnDefinitions.Add(new ColumnDefinition());
            }

            int row = 0;
            int col = 0;
            foreach (var item in listDictionary)
            {
                if (col == 8)
                {
                    row++;
                    col = 0;
                    var button = new Button() { Content = item.Key, Command = AddCommand, CommandParameter = item.Key, Width = 70, Height = 40};
                    Grid.SetColumn(button, col);
                    Grid.SetRow(button, row);
                    grid.Children.Add(button);
                    col ++;
                }
                else
                {
                    var button = new Button() { Content = item.Key, Command = AddCommand, CommandParameter = item.Key, Width = 70, Height = 40 };
                    Grid.SetColumn(button, col);
                    Grid.SetRow(button, row);
                    grid.Children.Add(button);
                    col++;
                }
                //var checkBox = new CheckBox() { Content = item.Key, Command = AddCommand , CommandParameter = item.Key};
                //DynamicControls.Add(grid);
            }

            DynamicControls.Add(grid);
        }
        #region Command

        public ICommand SPTInputCommand
        {
            get => new DelegateCommand(() => {
                OpenFileDialog dialog = new OpenFileDialog
                {
                    Filter = "All Files|*.*",

                };

                if (dialog.ShowDialog() == true && !string.IsNullOrWhiteSpace(dialog.FileName))
                {
                    // 获取用户选择的文件路径
                    FileName = dialog.FileName;
                    ControlTxT controlTxT = new ControlTxT();

                    listDictionary = controlTxT.ReadText(FileName);
                }
                InitialGrid();
            });
        }

        public ICommand StateCheckCommand
        {
            get => new DelegateCommand(() =>
            {
                if(SateChecked)
                {
                    visable = Visibility.Visible;
                }
                else
                {
                    visable = Visibility.Collapsed;
                }

            });
        }
        public ICommand TimeSpanCheckCommand
        {
            get => new DelegateCommand(() =>
            {
                if(TimeSpanIsChecked)
                {
                    TimeSpanVisable = Visibility.Visible;
                }
                else
                {
                    TimeSpanVisable = Visibility.Collapsed;
                }

            });
        }

        public ICommand IsCheckCommand
        {
            get => new DelegateCommand(() =>
            {
                if (IsChecked)
                {
                    visibility = Visibility.Visible;
                }
                else
                {
                    visibility = Visibility.Collapsed;
                }

            });
        }

        public ICommand MakeCommand
        {
            get => new DelegateCommand(() => {
            });
        }

        private DelegateCommand<string> addCommand;
        public DelegateCommand<string> AddCommand => addCommand ?? (addCommand = new DelegateCommand<string>(ExecuteMyCommand));

        private void ExecuteMyCommand(string sateName)
        {
            CalculateRAH calculateRAH = new CalculateRAH();
            ControlTxT controlTxT = new ControlTxT();
            CalculateValue calculateValue = GlobalEntity.calculateValue;
            calculateValue.sateliteDatas = listDictionary[sateName];
            calculateValue.buttonName = sateName;
            calculateValue.startTime = startTime;
            calculateValue.endTime = lastTime;
            // 在这里使用传递进来的参数
            Calculate calculate = new Calculate(calculateValue);
            List<numTest> numlist  =calculate.CalculateLocation(listDictionary[sateName]);
            //参数计算
            double delta_x = (GlobalEntity.configData.x_st2 - GlobalEntity.configData.x_st1) / lastTime;
            double delta_y = (GlobalEntity.configData.y_st2 - GlobalEntity.configData.y_st1) / lastTime;
            double delta_z = (GlobalEntity.configData.z_st2 - GlobalEntity.configData.z_st1) / lastTime;
            ControlExcel controlExcel = new ControlExcel();
            DateTime time = new DateTime(2020, 1, 1);
            DateTime StartDate = time.AddSeconds(startTime);
            int index = numlist.Select((numTest, i) => new { numTest = numTest, Index = i })
                             .Where(p => p.numTest.Time == StartDate)
                             .Select(p => p.Index)
                             .FirstOrDefault();
            int endIndex = index + lastTime;
            int preferIndex = index - PreferTime;
            string folderName = controlExcel.CreateFold(DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));

            if(MoveIsChecked)
                calculate.calcumn(numlist, folderName,sateName, index, endIndex, delta_x,delta_y,delta_z);
            if (SingleIsChecked)
                calculate.CalculateLocation(listDictionary[sateName], sateName, index, endIndex, folderName);
            if (IsChecked)
            {
                if (PreDel == true)
                {
                    calculate.CalculateLocation(calculateValue.sateliteDatas, calculateValue.buttonName, calculateValue.startTime, calculateValue.endTime, calculateValue.preferTime, DelTime, DelValue, true, folderName);
                }
                if (AftDel == true)
                {
                    calculate.CalculateLocation(calculateValue.sateliteDatas, calculateValue.buttonName, calculateValue.startTime, calculateValue.endTime, calculateValue.preferTime, DelTime, DelValue, false, folderName);
                }
            }
            if(SateChecked)
                controlTxT.insertUni(folderName, sateName + "_" + PreferTime.ToString(), numlist, preferIndex, endIndex);
            if (RAHIsChecked) 
            {
                List<numTest> numTests = calculate.CalculateLocation(listDictionary[sateName]);
                List<TD> uptDs = calculate.calcumn(numTests,GlobalEntity.configData.fu_up,GlobalEntity.configData.ff_down);
                List<TD> douwntDs = calculate.calcumn(numTests, GlobalEntity.configData.fu_down, GlobalEntity.configData.ff_up);
                List<numTest> EALists = calculateRAH.Calculate(numTests);
                List<downLinkData> downLinkDatas = calculateRAH.CalculateDownLink(numTests);
                List<UpLinkData> upLinkDatas = calculateRAH.CalculateUPLink(numTests);
                List<SwayData> swayDatas = calculateRAH.CalculateSway(numTests);
                controlExcel.insertRAHIntoExcel(folderName, sateName + "-"+ DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"), EALists ,downLinkDatas,upLinkDatas);
                //controlExcel.insertIntoExcel2Sheet(folderName, sateName + "-2sheet-all" , EALists, downLinkDatas, upLinkDatas, uptDs);
                controlExcel.insertIntoExcel2Sheet(folderName, sateName + "-2sheet-check", EALists, downLinkDatas, upLinkDatas, swayDatas, uptDs, douwntDs, index, endIndex);

            }
            if (RatioIsChecked)
            {
                List<numTest> numTests = calculate.CalculateLocation(listDictionary[sateName]);
                List<downLinkData> downLinkDatas = calculateRAH.CalculateDownLink(numTests);
                List<UpLinkData> upLinkDatas = calculateRAH.CalculateUPLink(numTests);
                //controlTxT.insertTXT(downLinkDatas, upLinkDatas, folderName);
            }
            if (TimeSpanIsChecked)
            {
                List<numTest> numTests = calculate.CalculateLocation(listDictionary[sateName],timeSpan);
                List<downLinkData> downLinkDatas = calculateRAH.CalculateDownLink(numTests);
                List<UpLinkData> upLinkDatas = calculateRAH.CalculateUPLink(numTests);
                List<List<TD>> tDLists1 = calculate.calcumnLoad(numTests,GlobalEntity.configData.fu_down,GlobalEntity.configData.ff_up);
                List<List<TD>> tDLists2 = calculate.calcumnLoad(numTests,GlobalEntity.configData.fu_up,GlobalEntity.configData.ff_down);
                index = numTests.Select((numTest, i) => new { numTest = numTest, Index = i })
                             .Where(p => p.numTest.Time == StartDate)
                             .Select(p => p.Index)
                             .FirstOrDefault();
                endIndex = index + (int)(lastTime / timeSpan);
                controlTxT.insertASO127(folderName, sateName + "_前向", tDLists1[0], tDLists1[1], downLinkDatas, index, endIndex, timeSpan);
                controlTxT.insertASO472(folderName, sateName + "_反向", tDLists2[0], tDLists2[1], upLinkDatas, index, endIndex, timeSpan);
                controlTxT.insertTXT(downLinkDatas, upLinkDatas, folderName, index, endIndex);
            }

            MessageBox.Show(folderName);
        }
        #endregion
    }
}
